package com.abe.libcore.base.http.converter;


import android.support.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

public class BaseConverterFactory extends Converter.Factory {
    private static final Converter.Factory normalFactory = ScalarsConverterFactory.create();
    private static final Converter.Factory xmlFactory = SimpleXmlConverterFactory.create();
    private static Converter.Factory jsonFactory = GsonConverterFactory.create(defaultGson());

    public static BaseConverterFactory create(Gson gson) {
        jsonFactory = GsonConverterFactory.create();
        return new BaseConverterFactory();
    }

    public static BaseConverterFactory create() {
        return new BaseConverterFactory();
    }

    @Nullable
    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        for (Annotation annotation : annotations) {
            if (!(annotation instanceof ResponseFormat)) {
                continue;
            }
            String value = ((ResponseFormat) annotation).value();
            switch (value) {
                case ResponseFormat.Normal:
                    return normalFactory.responseBodyConverter(type, annotations, retrofit);
                case ResponseFormat.JSON:
                    return jsonFactory.responseBodyConverter(type, annotations, retrofit);
                case ResponseFormat.XML:
                    return xmlFactory.responseBodyConverter(type, annotations, retrofit);
            }
        }
        return null;
    }

    private static Gson defaultGson() {
        GsonBuilder builder = new GsonBuilder();
        return builder.serializeNulls().create();
    }
}